package com.asm.slidingmenu;

import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.crypto.spec.IvParameterSpec;

import com.asm.DBloader.ASM_AVTemp;
import com.asm.DBloader.ASM_AVTempDS;
import com.asm.DBloader.ASM_DBlistDS;
import com.asm.DBloader.ASM_FAreaDS;
import com.asm.DBloader.ASM_FAvDet;
import com.asm.DBloader.ASM_FAvDetDS;
import com.asm.DBloader.ASM_FAvHed;
import com.asm.DBloader.ASM_FAvHedDS;
import com.asm.DBloader.ASM_FBrandDS;
import com.asm.DBloader.ASM_FCompanyBranch;
import com.asm.DBloader.ASM_FCompanyBranchDS;
import com.asm.DBloader.ASM_FDaynPrdHedDS;
import com.asm.DBloader.ASM_FRouteDS;
import com.asm.DBloader.ASM_FdebtorDS;
import com.asm.DBloader.ASM_UsersettingsDS;
import com.asm.DBloader.ASM_fCompanySettingDS;
import com.asm.DBloader.ASM_fDaynPrdDet;
import com.asm.DBloader.ASM_fDaynPrdDetDS;
import com.asm.DBloader.ASM_fItems;
import com.asm.DBloader.ASM_fItemsDS;
import com.asm.DBloader.ASM_fReasonDS;
import com.asm.DBloader.ASM_fSalRepDS;
import com.asm.slidingmenu.adapter.AVSheetAdapter;
import com.asm.slidingmenu.adapter.AVSheetLoadItemAdapter;
import com.dspl.asmswd.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class ASM_AVSheet_fragment extends Fragment implements OnClickListener {
	String ASMCode =null;
	public String brandcode;
	public static String details;
	String status = null;
	String newsalse = null;
	String HItems = null;
	String UItems = null;
	String VItems = null;
	String statusUA = null;
	String statusHA = null;
	String statusVA = null;
	private ViewGroup mContainerView;
	public static ArrayList<ASM_AVTemp> list;
	ListView lvInvoiceList;
	View rootView; 
	String cSettingcode = "ASMAVSHEET";
	String empty = "empty";
	public  ASM_AVSheet_fragment()
	{
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setHasOptionsMenu(true); 
		 rootView = inflater.inflate(R.layout.asm_fragment_avsheet, container,false);
		mContainerView = (ViewGroup)rootView.findViewById(R.id.container);
		
		
		ASM_UsersettingsDS ds2=new ASM_UsersettingsDS(getActivity());
		ASMCode = ds2.getASMCode(); 
		
		loadhistory();
		return rootView;
		
	
	}
	
	public void addAVsheet(String Status,final String UpdateRefno) 
	{
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.asm_dialog_avsheet);
		dialog.setCancelable(false);
		
		lvInvoiceList = (ListView)dialog.findViewById(R.id.listView1);
		Button btnsave = (Button)dialog.findViewById(R.id.btnsave);	
		Button btnclear = (Button)dialog.findViewById(R.id.btnclear);
		final EditText txtrefno = (EditText)dialog.findViewById(R.id.txtrefno);
		final EditText txndate = (EditText)dialog.findViewById(R.id.EditText01);
		final AutoCompleteTextView searchcustomer = (AutoCompleteTextView)dialog.findViewById(R.id.searchcustomer);
		final AutoCompleteTextView Teratory = (AutoCompleteTextView)dialog.findViewById(R.id.AutoCompleteTextView01);
		final AutoCompleteTextView root = (AutoCompleteTextView)dialog.findViewById(R.id.AutoCompleteTextView02);
		final EditText Remark = (EditText)dialog.findViewById(R.id.EditText02);
		final Spinner spinerselect = (Spinner)dialog.findViewById(R.id.spinerselect);
		Button btncancel = (Button)dialog.findViewById(R.id.btncancel);

		if(Status.equals("add"))
		{
			
		
		
		//final String ItemCode;
		final String Refno = refnogenrator(cSettingcode,empty);
		txtrefno.setText(Refno);
		txndate.setText(getCurrentTimeString().toString());
	
		
		
	
		
		ASM_FAreaDS dsa=new ASM_FAreaDS(getActivity());
		ArrayList<String> list5 =dsa.getArea();
		ArrayAdapter<String> categoriesAdapter5 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.item, list5);
		Teratory.setAdapter(categoriesAdapter5);

		Teratory.setOnItemClickListener(new OnItemClickListener() 
		{

			@Override
			 public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) 
			{
				// TODO Auto-generated method stub

				
				ASM_FRouteDS dsf=new ASM_FRouteDS(getActivity());
				ArrayList<String> list6 =dsf.getRoute(parent.getItemAtPosition(position).toString().split("-:-")[1].toString().trim());
				ArrayAdapter<String> categoriesAdapter6 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.item, list6);
				root.setAdapter(categoriesAdapter6);
				root.setOnItemClickListener(new OnItemClickListener() 
				{

					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long rowId)
					{
						// TODO Auto-generated method stub
						//ItemCode = parent.getItemAtPosition(position).toString().split("-:-")[1].toString().trim();
						ASM_FdebtorDS dsf=new ASM_FdebtorDS(getActivity());
						ArrayList<String> list6 =dsf.getselectDeb(parent.getItemAtPosition(position).toString().split("-:-")[1].toString().trim());
						ArrayAdapter<String> categoriesAdapter6 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.item, list6);
						searchcustomer.setAdapter(categoriesAdapter6);
						searchcustomer.setOnItemClickListener(new OnItemClickListener()  
						{

							@Override
							public void onItemClick(AdapterView<?> parent,View view, int position, long id) 
							{
								// TODO Auto-generated method stub
								
							}
							
						}); 
					
					}
				
					
				}); 
			}
			
		}); 

	
	    ASM_FBrandDS dsc=new ASM_FBrandDS(getActivity());
	    ArrayList<String> list6 =dsc.getBrand();
		ArrayAdapter<String> categoriesAdapter6 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.item, list6);
		spinerselect.setAdapter(categoriesAdapter6);
		
		final TableLayout stk = (TableLayout)dialog.findViewById(R.id.table_main);
		spinerselect.setOnItemSelectedListener(new OnItemSelectedListener() 
		{
			
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,int position, long id) 
			{

				// TODO Auto-generated method stub
			
				 lvInvoiceList.clearTextFilter();
				  ASM_fItemsDS dsg=new ASM_fItemsDS(getActivity());
				  ArrayList<ASM_fItems> list7 =dsg.getFitems(parent.getItemAtPosition(position).toString().split("-:-")[1].trim().toString());
				  
				  ASM_AVTempDS dsgw=new ASM_AVTempDS(getActivity());
				  
				  ArrayList<ASM_AVTemp> list8 = dsgw.getTempdetail(parent.getItemAtPosition(position).toString().split("-:-")[1].trim().toString(),refnogenrator(cSettingcode,empty));
				  lvInvoiceList.setAdapter(new AVSheetAdapter(getActivity(),list8));
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) 
			{
				// TODO Auto-generated method stub

			}
		});
		

		
		btnsave.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				ASM_AVTempDS DS5 = new ASM_AVTempDS(getActivity());
				DS5.Create(AVSheetAdapter.list);
				if (Teratory.getText().length()!=0 && root.getText().length()!=0 && searchcustomer.getText().length()!=0) {
					
				
					if(DS5.Create(AVSheetAdapter.list)>0){
						ASM_AVTempDS ds=new ASM_AVTempDS(getActivity());
						ArrayList<String> list =ds.getSaveTemp(Refno);
							if(!list.toString().equals("[]"))
								{

									try {
									GPSTracker gps = new GPSTracker(getActivity());
					
							      	ASM_FAvHed asDblist3 = new ASM_FAvHed();
									ASM_FAvHedDS DS4 = new ASM_FAvHedDS(getActivity());
									
									ASM_FAvDet asDblist4 = new ASM_FAvDet();
									asDblist3.setASM_FAVHED_REFNO(txtrefno.getText().toString().trim());
									asDblist3.setASM_FAVHED_ADDUSER(ASMCode.toString());
									asDblist3.setASM_FAVHED_REMARKS(Remark.getText().toString().trim());
									asDblist3.setASM_FAVHED_TXNDATE(txndate.getText().toString());
									asDblist3.setASM_FAVHED_ADDDATE(txndate.getText().toString());
									asDblist3.setASM_FAVHED_ADDMACH("");
									asDblist3.setASM_FAVHED_TERATORY(Teratory.getText().toString().trim());
									asDblist3.setASM_FAVHED_ROOT(root.getText().toString().trim());
									asDblist3.setASM_FAVHED_DEBTOR(searchcustomer.getText().toString());
									asDblist3.setASM_FAVHED_BRAND(spinerselect.getSelectedItem().toString().trim());
									asDblist3.setASM_FAVHED_ISSYNCED("0");
										 if(gps.canGetLocation())
										 {
							               	 double lati = gps.getLatitude();
							                 double longi = gps.getLongitude();
							                 asDblist3.setASM_FAVHED_Longitude(Double.toString(longi));
							                 asDblist3.setASM_FAVHED_Latitude(Double.toString(lati));
							                 Toast.makeText(getActivity(), "Your Location is - \nLat: " + lati + "\nLong: " + longi, Toast.LENGTH_LONG).show();   
										 }
											 else
											 {
								                   gps.showSettingsAlert();
								                   double lati = gps.getLatitude();
								                   double longi = gps.getLongitude();
								                   asDblist3.setASM_FAVHED_Longitude(Double.toString(longi));
									               asDblist3.setASM_FAVHED_Latitude(Double.toString(lati));
								                   Toast.makeText(getActivity(), "Your Location is - \nLat: " + lati + "\nLong: " + longi, Toast.LENGTH_LONG).show(); 
								               }

													if(DS4.Create(asDblist3)>0)
													{
														
													ASM_AVTempDS dsf=new ASM_AVTempDS(getActivity());
													ArrayList<ASM_AVTemp> list6 =dsf.GetTempDetails(txtrefno.getText().toString().trim());
									
													ASM_FAvDetDS sav = new ASM_FAvDetDS(getActivity());
													for (int i = 0; i < list6.size(); i++) 
													{
														asDblist4.setASM_FAVDET_REFNO(list6.get(i).getAsmavTempRefno());
														asDblist4.setASM_FAVDET_TXNDATE(txndate.getText().toString());
														asDblist4.setASM_FAVDET_ITEMCODE(list6.get(i).getAsmavTempItemcode());
														asDblist4.setASM_FAVDET_ITEMNAME(list6.get(i).getAsmavTempItemname());
														asDblist4.setASM_FAVDET_COMPSTATUS(list6.get(i).getAsmavTempStatus());
														asDblist4.setASM_FAVDET_COMPPROD(list6.get(i).getAsmavTempNewsales());
														asDblist4.setASM_FAVDET_UITEMS(list6.get(i).getAsmavTempUitems());
														asDblist4.setASM_FAVDET_USTATUS(list6.get(i).getAsmavTempUstatus());
														asDblist4.setASM_FAVDET_HITEMS(list6.get(i).getAsmavTempHitems());
														asDblist4.setASM_FAVDET_HSTATUS(list6.get(i).getAsmavTempHstatus());
														asDblist4.setASM_FAVDET_VITEMS(list6.get(i).getAsmavTempVitems());
														asDblist4.setASM_FAVDET_VSTATUS(list6.get(i).getAsmavTempVstatus());
														asDblist4.setASM_FAVDET_ACTIVESTATE("0");
													
														sav.Create(asDblist4);
													}
				
													ASM_AVTemp delRef = new ASM_AVTemp();
													delRef.setAsmavTempRefno(txtrefno.getText().toString().trim());
													ASM_AVTempDS ds2=new ASM_AVTempDS(getActivity());
													ds2.RefNoReset(delRef);
													
													addItem(txtrefno.getText().toString().trim(), searchcustomer.getText().toString());
													String seperate = txtrefno.getText().toString().trim().substring(5);
													int incriment = Integer.parseInt(seperate);
													int newincriment = incriment + 1;
													ASM_FCompanyBranch asDblist1 = new ASM_FCompanyBranch();
													ASM_FCompanyBranchDS DS1 = new ASM_FCompanyBranchDS(getActivity());
													
													asDblist1.setAsmFCompanyBranch_cSettingsCode(cSettingcode);
													asDblist1.setAsmFCompanyBranch_nNumVal(Integer.toString(newincriment));
													DS1.Create(asDblist1);
	
													}
									          	    
													} 
													catch (Exception e) 
													{
														Toast.makeText(getActivity(), "Record save not sucess...Contact your administrator"+e.toString(), 
																   Toast.LENGTH_LONG).show();
														dialog.dismiss();
														// TODO: handle exception
													}
													dialog.dismiss();
				
								}else 
									{
									AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
									builder1.setTitle("ERROR");
									builder1.setIcon(R.drawable.ic_error);
						            builder1.setMessage("No Added Item For the Save...");
						            builder1.setCancelable(true);
						            builder1.setPositiveButton("OK",
						                new DialogInterface.OnClickListener()
						            {
						                public void onClick(DialogInterface dg, int id) 
						                {
						                	dg.dismiss();
				
						                }
						            });
						            AlertDialog alert11 = builder1.create();
						            alert11.show();
					
									}
				
					}
				// 
				}else {
					errormsg("Teratory,Root or Customer");
				}

			}
		});
		
		btncancel.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				ASM_AVTempDS ds2=new ASM_AVTempDS(getActivity());
          	 //   ds2.Delete(txtrefno.getText().toString().trim());
				dialog.dismiss();
				loadhistory();
			}
		});
		btnclear.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				
				searchcustomer.setText("");
				Teratory.setText("");
				root.setText("");
				Remark.setText("");

			}
		});
		
		btncancel.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				ASM_AVTempDS ds2=new ASM_AVTempDS(getActivity());
				//String k  = ds2.CheckDetails(txtrefno.getText().toString().trim());
				if(ds2.CheckDetails(txtrefno.getText().toString().trim())!=null)
				{
					//CancelDialog();
					
					AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
					builder1.setTitle("ATTENTION..!");
					builder1.setIcon(R.drawable.ic_attention);
		            builder1.setMessage("This Action Will Be Delete All the Newly Entered Record..Are You Sure..?");
		            builder1.setCancelable(true);
		            builder1.setPositiveButton("YES",
		                new DialogInterface.OnClickListener()
		            {
		                public void onClick(DialogInterface dg, int id) 
		                {
		                	mContainerView.removeAllViews();
		                	ASM_AVTempDS ds2=new ASM_AVTempDS(getActivity());
			          	//    ds2.Delete(txtrefno.getText().toString().trim());
							dialog.dismiss();
		                	dg.dismiss();
		                	loadhistory();
		           
		                }
		            });
		            builder1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
		            AlertDialog alert11 = builder1.create();
		            alert11.show();	
				}else 
				{
					mContainerView.removeAllViews();
					dialog.dismiss();
					loadhistory();
				}
			}
		});
				
		dialog.show();
		

		
		}
	
	}
	
	public String refnogenrator(String cSettingsCode,String ASMPreFix) 
	{
		
		
		ASM_fCompanySettingDS ds1=new ASM_fCompanySettingDS(getActivity());
		String refcode =ds1.getFcompanyDetails(cSettingsCode,ASMCode);
		
		ASM_FCompanyBranchDS ds=new ASM_FCompanyBranchDS(getActivity());
		String tempRepExpenseSerialStr = ds.getFcompanybranch(cSettingsCode);
		if(tempRepExpenseSerialStr==null)
		{
			tempRepExpenseSerialStr = "1";
		}
		
		String currentExpenseRefCode = null;
		
		

		try {
			if (tempRepExpenseSerialStr.length() == 0) 
			{
				String newInvNumberStr = "0000000" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else if (tempRepExpenseSerialStr.length() == 1)
			{
				String newInvNumberStr = "000000" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else if (tempRepExpenseSerialStr.length() == 2) 
			{
				String newInvNumberStr = "00000" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			}
			else if (tempRepExpenseSerialStr.length() == 3) 
			{
				String newInvNumberStr = "0000" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else if (tempRepExpenseSerialStr.length() == 4) 
			{
				String newInvNumberStr = "000" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else if (tempRepExpenseSerialStr.length() == 5) 
			{
				String newInvNumberStr = "00" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else if (tempRepExpenseSerialStr.length() == 5) 
			{
				String newInvNumberStr = "0" + tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			} 
			else 
			{
				String newInvNumberStr = tempRepExpenseSerialStr;
				currentExpenseRefCode = refcode.trim() + "/"+ newInvNumberStr;
			}
		} catch (Exception e) {

		}

		
		
		return currentExpenseRefCode;
	}
	private String getCurrentTimeString() 
	{
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy/MM/dd");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		String cusDate = date_to_string;
		return cusDate;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) 
		{
		case R.id.action_add_item:
			addAVsheet("add","");
			return true;
				default:
			return super.onOptionsItemSelected(item);
		}
	}
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
	     if(keyCode==KeyEvent.KEYCODE_BACK)
	         Toast.makeText(getActivity(), "Use Home Button",      
	      Toast.LENGTH_LONG).show();

	     return false;
	        // Disable back button..............
	 }
	 public void onBackPressed()
	 {

	    //thats it
	 }

	 public void errormsg(String msg) 
	 {
			AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
			builder1.setTitle("ERROR");
			builder1.setIcon(R.drawable.ic_error);
            builder1.setMessage(msg +" Not selected Please Select... ");
            builder1.setCancelable(true);
            builder1.setPositiveButton("OK",
                new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dg, int id) 
                {
                	dg.dismiss();
           
                }
            });
            AlertDialog alert11 = builder1.create();
            alert11.show();	
				
	}
	 
	 public void errormsg2() 
	 {
			AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
			builder1.setTitle("ERROR");
			builder1.setIcon(R.drawable.ic_error);
            builder1.setMessage("This Item Already added...");
            builder1.setCancelable(true);
            builder1.setPositiveButton("OK",
                new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dg, int id) 
                {
                	dg.dismiss();
           
                }
            });
            AlertDialog alert11 = builder1.create();
            alert11.show();	
				
	}
	 
	 
	    private void addItem(String txtrefno,String getSelectedReson) 
	    {
	        // Instantiate a new "row" view.
	        final ViewGroup newView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(
	                R.layout.list_item_example, mContainerView, false);
	        ((TextView) newView.findViewById(android.R.id.text1)).setText("");
	        // Set the text in the new row to a random country.
	       ((TextView) newView.findViewById(android.R.id.text1)).setText(txtrefno.toString()+" -:- "+getSelectedReson.toString());

	        // Set a click listener for the "X" button in the row that will remove the row.
	        newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() 
	        {
	            @Override
	            public void onClick(View view) 
	            {
	        		AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
	        		builder1.setTitle("ATTENTION..!");
	    			builder1.setIcon(R.drawable.ic_attention);
		            builder1.setMessage("Are you Sure Want to Delete This Record..? This Step Can't Be Reverse..");
		            builder1.setCancelable(true);
		            builder1.setPositiveButton("OK",
		            new DialogInterface.OnClickListener()
		            {
		                public void onClick(DialogInterface dg, int id) 
		                {
		                	   mContainerView.removeView(newView);
		                	   String refno  = ((TextView) newView.findViewById(android.R.id.text1)).getText().toString().substring(0, 12);
		                	   ASM_FAvDetDS ds2=new ASM_FAvDetDS(getActivity());
		                	   ASM_FAvHedDS ds3=new ASM_FAvHedDS(getActivity());
		                	   ds2.Delete(refno);
		                	   ds3.Delete(refno);

		                       if (mContainerView.getChildCount() == 0) 
		                       {
		                           
		                       }
		                	dg.dismiss();
		           
		                }
		            });
		            
		            builder1.setNegativeButton("NO",  
		            new DialogInterface.OnClickListener()
		            {
		                public void onClick(DialogInterface dg, int id) 
		                {
		                dg.dismiss();
		                }
		            });
		            AlertDialog alert11 = builder1.create();
		            alert11.show();
	                // Remove the row from its parent (the container view).
	                // Because mContainerView has android:animateLayoutChanges set to true,
	                // this removal is automatically animated.
	             
	            }
	        });
	        
	        newView.findViewById(R.id.view_button).setOnClickListener(new View.OnClickListener() {
				
	    			@Override
	    			public void onClick(View v) 
	    			{

	    				
	    				
	    				String refno  = ((TextView) newView.findViewById(android.R.id.text1)).getText().toString().substring(0, 12);
	    				ViewDetails(refno);
	    				// TODO Auto-generated method stub
	    			
	    			}
	    		});
	        

	        mContainerView.addView(newView, 0);
	    }
		public void loadhistory() 
		{

			ASM_FAvHedDS ds3=new ASM_FAvHedDS(getActivity());
			ArrayList<String> list1 =ds3.getfAVHedfull();
			ArrayAdapter<String> categoriesAdapter1 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.item, list1);

			
			for (int i = 0; i < categoriesAdapter1.getCount(); i++) 
			{
				addItem(categoriesAdapter1.getItem(i).split("~")[0].toString(),categoriesAdapter1.getItem(i).split("~")[5].toString());
			}

			
		}
		
		
		
		public void ViewDetails(String RefNo) 
		{
			
			 final Dialog dialog = new Dialog(getActivity());
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.asm_dailogavsheetview);
			dialog.setCancelable(false);
			dialog.show();
			
			TextView txtRefno = (TextView)dialog.findViewById(R.id.txtRefno);
			TextView txtDate = (TextView)dialog.findViewById(R.id.txtDate);
			TextView txtRemk = (TextView)dialog.findViewById(R.id.txtRemk);
			TextView txtTertor = (TextView)dialog.findViewById(R.id.txtTertor);
			TextView txtRoot = (TextView)dialog.findViewById(R.id.txtRoot);
			TextView txtcus = (TextView)dialog.findViewById(R.id.txtcus);
			TextView txtBrand = (TextView)dialog.findViewById(R.id.txtBrand);

			
			
			
			ASM_FAvHedDS ds3=new ASM_FAvHedDS(getActivity());
			ArrayList<ASM_FAvHed> list1 =ds3.getfAVHed(RefNo);
			
			txtRefno.setText(list1.get(0).getASM_FAVHED_REFNO());
			txtDate.setText(list1.get(0).getASM_FAVHED_TXNDATE());
			txtRemk.setText(list1.get(0).getASM_FAVHED_REMARKS());
			txtTertor.setText(list1.get(0).getASM_FAVHED_TERATORY());
			txtRoot.setText(list1.get(0).getASM_FAVHED_ROOT());
			txtcus.setText(list1.get(0).getASM_FAVHED_DEBTOR());
			txtBrand.setText(list1.get(0).getASM_FAVHED_BRAND());
			
			
			
			
			TableLayout stk = (TableLayout)dialog.findViewById(R.id.table_main);
	        TableRow tbrow0 = new TableRow(getActivity());
	        tbrow0.setGravity(Gravity.RIGHT);
	        
        
	        TextView tv0 = new TextView(getActivity());
	        tv0.setText(" ITEM NAME ");
	        tv0.setClickable(false);
	        
	        tv0.setTextSize(18);
	        tv0.setTextColor(Color.BLUE);
	        tv0.setGravity(Gravity.CENTER_VERTICAL);
	        tbrow0.addView(tv0);
	        
	        TextView tv2 = new TextView(getActivity());
	        tv2.setText(" STATUS ");
	        tv2.setClickable(false);
	        tv2.setTextSize(18);
	        tv2.setGravity(Gravity.CENTER_VERTICAL);
	        tv2.setTextColor(Color.BLUE);
	        tbrow0.addView(tv2);
	        
	        TextView tv6 = new TextView(getActivity());
	        tv6.setText(" NEW SALES");
	        tv6.setClickable(false);
	        tv6.setTextSize(18);
	        tv6.setGravity(Gravity.CENTER_VERTICAL);
	        tv6.setTextColor(Color.BLUE);
	        tbrow0.addView(tv6);
	        
	        TextView tv3 = new TextView(getActivity());
	        tv3.setText(" U.ITEM ");
	        tv3.setClickable(false);
	        tv3.setTextSize(18);
	        tv3.setGravity(Gravity.CENTER_VERTICAL);
	        tv3.setTextColor(Color.BLUE);
	        tbrow0.addView(tv3);
		    
	        TextView tv5 = new TextView(getActivity());
	        tv5.setText(" U.STATUS ");
	        tv5.setClickable(false);
	        tv5.setTextSize(18);
	        tv5.setGravity(Gravity.CENTER_VERTICAL);
	        tv5.setTextColor(Color.BLUE);
	        tbrow0.addView(tv5);
	        
	        TextView tv4 = new TextView(getActivity());
	        tv4.setText(" H.ITEM ");
	        tv4.setClickable(false);
	        tv4.setTextSize(18);
	        tv4.setGravity(Gravity.CENTER_VERTICAL);
	        tv4.setTextColor(Color.BLUE);
	        tbrow0.addView(tv4);
	        
	        TextView tv8 = new TextView(getActivity());
	        tv8.setText(" H.STATUS ");
	        tv8.setClickable(false);
	        tv8.setTextSize(18);
	        tv8.setGravity(Gravity.CENTER_VERTICAL);
	        tv8.setTextColor(Color.BLUE);
	        tbrow0.addView(tv8);
	        
	        TextView tv7 = new TextView(getActivity());
	        tv7.setText(" V.ITEM ");
	        tv7.setClickable(false);
	        tv7.setTextSize(18);
	        tv7.setGravity(Gravity.CENTER_VERTICAL);
	        tv7.setTextColor(Color.BLUE);
	        tbrow0.addView(tv7);
	        
	        TextView tv9 = new TextView(getActivity());
	        tv9.setText(" V.STATUS ");
	        tv9.setClickable(false);
	        tv9.setTextSize(18);
	        tv9.setGravity(Gravity.CENTER_VERTICAL);
	        tv9.setTextColor(Color.BLUE);
	        tbrow0.addView(tv9);

	        stk.addView(tbrow0);
	        
	        
	        ASM_FAvDetDS ds4=new ASM_FAvDetDS(getActivity());
			ArrayList<ASM_FAvDet> list2 =ds4.getfAVDet(RefNo);
			
			   
	            
	        

			
			for (int i = 0; i <list2.size(); i++) 
			{
				
				//RefNo,Itemcode,Itemname,Cmpstatus,cmpprod,Uitems,Ustatus,Hitems,Hstaus,Vitems,Vstatus
			  TableRow tbrow = new TableRow(getActivity());
			  TextView t1v = new TextView(getActivity());     
		      t1v.setText(" "+list2.get(i).getASM_FAVDET_ITEMNAME());
		      t1v.setTextColor(Color.WHITE);
		      t1v.setTextSize(17);
		      t1v.setGravity(Gravity.LEFT);
		      t1v.setClickable(true);
		      tbrow.addView(t1v);
				
		      TextView t2v = new TextView(getActivity());
			  t2v.setTextColor(Color.WHITE);
	          t2v.setText(list2.get(i).getASM_FAVDET_COMPSTATUS());
	          t2v.setTextSize(17);
	          t2v.setGravity(Gravity.CENTER);
	          t2v.setClickable(true);
	          tbrow.addView(t2v);
	          
	          TextView t3v = new TextView(getActivity());
	          t3v.setTextColor(Color.WHITE);
	          t3v.setText(list2.get(i).getASM_FAVDET_COMPPROD());
	          t3v.setTextSize(17);
	          t3v.setGravity(Gravity.CENTER);
	          t3v.setClickable(true);
	          tbrow.addView(t3v);
	          
	          
	          TextView t4v = new TextView(getActivity());
	          t4v.setTextColor(Color.WHITE);
	          t4v.setText(list2.get(i).getASM_FAVDET_UITEMS());
	          t4v.setTextSize(17);
	          t4v.setGravity(Gravity.CENTER);
	          t4v.setClickable(true);
	          tbrow.addView(t4v);
          
	          TextView t5v = new TextView(getActivity());
	          t5v.setTextColor(Color.WHITE);
	          t5v.setText(list2.get(i).getASM_FAVDET_USTATUS());
	          t5v.setTextSize(17);
	          t5v.setGravity(Gravity.CENTER);
	          t5v.setClickable(true);
	          tbrow.addView(t5v);
         
	          TextView t6v = new TextView(getActivity());
	          t6v.setTextColor(Color.WHITE);
	          t6v.setText(list2.get(i).getASM_FAVDET_HITEMS());
	          t6v.setTextSize(17);
	          t6v.setGravity(Gravity.CENTER);
	          t6v.setClickable(true);
	          tbrow.addView(t6v);
          
	          TextView t7v = new TextView(getActivity());
	          t7v.setTextColor(Color.WHITE);
	          t7v.setText(list2.get(i).getASM_FAVDET_HSTATUS());
	          t7v.setTextSize(17);
	          t7v.setGravity(Gravity.CENTER);
	          t7v.setClickable(true);
	          tbrow.addView(t7v);
          
	          TextView t8v = new TextView(getActivity());
	          t8v.setTextColor(Color.WHITE);
	          t8v.setText(list2.get(i).getASM_FAVDET_VITEMS());
	          t8v.setTextSize(17);
	          t8v.setGravity(Gravity.CENTER);
	          t8v.setClickable(true);
	          tbrow.addView(t8v);
        
	          TextView t9v = new TextView(getActivity());
	          t9v.setTextColor(Color.WHITE);
	          t9v.setText(list2.get(i).getASM_FAVDET_VSTATUS());
	          t9v.setTextSize(17);
	          t9v.setGravity(Gravity.CENTER);
	          t9v.setClickable(true);
	          tbrow.addView(t9v);
	          stk.addView(tbrow);
	        // stk.addView(tbrow);
			}
			Button btnOK = (Button)dialog.findViewById(R.id.btnOK);
			btnOK.setOnClickListener(new View.OnClickListener()
			{
				
				@Override
				public void onClick(View v) 
				{
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
		}
		
		
		
		
		
		
		
		
		
		
		  @Override
			public void onStop() 
			  {
			  super.onStop();
			  ASM_AVTempDS ds2=new ASM_AVTempDS(getActivity());
			//  ds2.DeleteAllrec();

			   }

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
		}

}
